﻿Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Text.RegularExpressions
Imports System.Threading
Imports System.Windows.Forms
Imports System.Net.Sockets
Imports System.IO
Imports System.Net
Imports MySql.Data
Imports MySql.Data.MySqlClient
Imports System.Data.DataTable
Imports System.Data.SqlClient

Namespace Othello
    ''' <summary>
    ''' Summary description for Reversi.
    ''' </summary>
    Public Class ReversiForm

        Inherits System.Windows.Forms.Form
        ' Background Worker
        Private WithEvents BW As System.ComponentModel.BackgroundWorker
        ' Main menu.
        Private mainMenu As System.Windows.Forms.MainMenu
        Private gameMenuItem As System.Windows.Forms.MenuItem
        Private newGameMenuItem As System.Windows.Forms.MenuItem
        Private joinGameMenuItem As System.Windows.Forms.MenuItem
        Private resignGameMenuItem As System.Windows.Forms.MenuItem
        Private gameSeparator1MenuItem As System.Windows.Forms.MenuItem
        Private optionsMenuItem As System.Windows.Forms.MenuItem
        Private statisticsMenuItem As System.Windows.Forms.MenuItem
        Private gameSeparator2MenuItem As System.Windows.Forms.MenuItem
        Private exitMenuItem As System.Windows.Forms.MenuItem
        Private helpMenuItem As System.Windows.Forms.MenuItem
        Private helpTopicsMenuItem As System.Windows.Forms.MenuItem
        Private helpSeparatorMenuItem As System.Windows.Forms.MenuItem
        Private aboutMenuItem As System.Windows.Forms.MenuItem

        ' Tool bar.
        Private playToolBar As System.Windows.Forms.ToolBar
        Private playImageList As System.Windows.Forms.ImageList
        Private newGameToolBarButton As System.Windows.Forms.ToolBarButton
        Private resignGameToolBarButton As System.Windows.Forms.ToolBarButton
        Private separatorToolBarButton As System.Windows.Forms.ToolBarButton

        ' Board display.
        Private boardPanel As System.Windows.Forms.Panel
        Private cornerLabel As System.Windows.Forms.Label
        Private squaresPanel As System.Windows.Forms.Panel

        ' Information display.
        Private infoPanel As System.Windows.Forms.Panel
        Private whiteTextLabel As System.Windows.Forms.Label
        Private whiteCountLabel As System.Windows.Forms.Label
        Private blackTextLabel As System.Windows.Forms.Label
        Private blackCountLabel As System.Windows.Forms.Label
        Private currentColorTextLabel As System.Windows.Forms.Label
        Private currentColorPanel As System.Windows.Forms.Panel
        Private moveListView As System.Windows.Forms.ListView
        Private moveNullColumn As System.Windows.Forms.ColumnHeader
        Private moveNumberColumn As System.Windows.Forms.ColumnHeader
        Private movePlayerColumn As System.Windows.Forms.ColumnHeader
        Private movePositionColumn As System.Windows.Forms.ColumnHeader

        ' Status display.
        Private statusPanel As System.Windows.Forms.Panel
        Private statusLabel As System.Windows.Forms.Label
        Private statusProgressBar As System.Windows.Forms.ProgressBar

        'Declare Events
        Private Shadows Event Click(ByVal sender As Object, ByRef e As System.EventArgs)
        Private Shadows Event MouseMove(ByVal sender As Object, ByRef e As System.EventArgs)
        Private Shadows Event MouseLeave(ByVal sender As Object, ByRef e As System.EventArgs)

        ''' <summary>
        ''' Required designer variable.
        ''' </summary>
        Private components As System.ComponentModel.Container = Nothing

        ' This enumeration should match the button order on the tool bar.
        Public Enum ToolBarButton
            NewGame
            ResignGame
        End Enum

        ' Defines the game states.
        Private Enum GameStates
            GameOver
            ' The game is over (also used for the initial state).
            InPlayerMove
            ' Waiting for the user to make a move.
            MoveCompleted
            ' A move has been completed.
        End Enum

        ' The game board.
        Private board As Board
        Private colLabels As Label(), rowLabels As Label()
        Private squareControls As SquareControl(,)

        ' Game options.
        Private options As New Options()

        ' Game statistics.
        Private statistics As New Statistics()

        ' Game parameters.
        Private gameState As GameStates
        Private currentColor As Integer
        Private moveNumber As Integer

        ' Defines the maximum move rank value (used for ranking an end game).
        Private Shared maxRank As Integer = System.Int32.MaxValue - 64

        ' For converting column numbers to letters and vice versa.
        Private Shared alpha As [String] = "ABCDEFGH"

        ' For getting moves via the keyboard.
        Private keyedColNumber As Integer
        Private keyedRowNumber As Integer

        ' Defines a structure for holding move history data.
        Private Structure MoveRecord
            Public board As Board
            Public currentColor As Integer
            Public moveListItem As ListViewItem

            Public Sub New(ByVal board As Board, ByVal currentColor As Integer, ByVal moveListItem As ListViewItem)
                Me.board = New Board(board)
                Me.currentColor = currentColor
                Me.moveListItem = moveListItem
            End Sub
        End Structure

        ' Defines an array for storing the move history.
        Private moveHistory As ArrayList

        ' Used to track which player made the last move.
        Private lastMoveColor As Integer

        ' Used to save statistics when undoing moves in a completed game.
        Private oldStatistics As Statistics

        ' For tracking the window location and size.
        Private windowSettings As Rectangle

        ' For loading and saving program settings.
        Private settings As ProgramSettings
        Private Shared ReadOnly programSettingsFileName As String = "Reversi.xml"

        ' The help file name.
        Private Shared ReadOnly helpFileName As String = "Reversi.chm"

        Public Sub New()
            '
            ' Required for Windows Form Designer support
            '
            InitializeComponent()

            ' TODO: Add any constructor code after InitializeComponent call
            '

            ' Create the game board.
            Me.board = New Board()

            ' Create the controls for each square, add them to the squares
            ' panel and set up event handling.
            Me.squareControls = New SquareControl(7, 7) {}
            Dim i As Integer, j As Integer
            For i = 0 To 7
                For j = 0 To 7
                    ' Create it.
                    Me.squareControls(i, j) = New SquareControl(i, j)
                    ' Position it.
                    Me.squareControls(i, j).Left = j * Me.squareControls(i, j).Width
                    Me.squareControls(i, j).Top = i * Me.squareControls(i, j).Height
                    ' Add it.
                    Me.squaresPanel.Controls.Add(Me.squareControls(i, j))

                    ' Add Handlers For Custom Events
                    AddHandler squareControls(i, j).Click, AddressOf SquareControl_Click
                    AddHandler squareControls(i, j).MouseMove, AddressOf SquareControl_MouseMove
                    AddHandler squareControls(i, j).MouseLeave, AddressOf SquareControl_MouseLeave

                Next
            Next
            ' Create the column and row labels.
            Me.colLabels = New Label(7) {}
            For i = 0 To 7
                ' Create a column label.
                Me.colLabels(i) = New Label()

                ' Set its display properties.
                Me.colLabels(i).Text = ReversiForm.alpha.Substring(i, 1)
                Me.colLabels(i).BackColor = Me.cornerLabel.BackColor
                Me.colLabels(i).ForeColor = Me.cornerLabel.ForeColor
                Me.colLabels(i).TextAlign = ContentAlignment.MiddleCenter

                ' Set its size and position.
                Me.colLabels(i).Width = Me.squareControls(0, 0).Width
                Me.colLabels(i).Height = Me.cornerLabel.Height
                Me.colLabels(i).Left = Me.cornerLabel.Width + i * Me.colLabels(0).Width
                Me.colLabels(i).Top = 0

                ' Add it.
                Me.boardPanel.Controls.Add(Me.colLabels(i))
            Next
            Me.rowLabels = New Label(7) {}
            For i = 0 To 7
                ' Create a row label.
                Me.rowLabels(i) = New Label()

                ' Set its display properties.
                Me.rowLabels(i).Text = (i + 1).ToString()
                Me.rowLabels(i).BackColor = Me.cornerLabel.BackColor
                Me.rowLabels(i).ForeColor = Me.cornerLabel.ForeColor
                Me.rowLabels(i).TextAlign = ContentAlignment.MiddleCenter

                ' Set its size and position.
                Me.rowLabels(i).Width = Me.cornerLabel.Height
                Me.rowLabels(i).Height = Me.squareControls(0, 0).Height
                Me.rowLabels(i).Left = 0
                Me.rowLabels(i).Top = Me.cornerLabel.Height + i * Me.rowLabels(0).Width

                ' Add it.
                Me.boardPanel.Controls.Add(Me.rowLabels(i))
            Next

            ' Initialize the game state.
            Me.gameState = GameStates.GameOver

            ' Initialize the window settings.
            Me.windowSettings = New Rectangle(Me.DesktopLocation.X, Me.DesktopLocation.Y, Me.ClientSize.Width, Me.ClientSize.Height)

            '            ' Load any saved program settings.
            Me.settings = New ProgramSettings(ReversiForm.programSettingsFileName)
            Me.LoadProgramSettings()
        End Sub

        ''' <summary>
        ''' Clean up any resources being used.
        ''' </summary>
        Protected Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If components IsNot Nothing Then
                    components.Dispose()
                End If
            End If
            MyBase.Dispose(disposing)
        End Sub

#Region "Windows Form Designer generated code"
        ''' <summary>
        ''' Required method for Designer support - do not modify
        ''' the contents of this method with the code editor.
        ''' </summary>
        Private Sub InitializeComponent()
            Me.components = New System.ComponentModel.Container()
            Dim resources As New System.Resources.ResourceManager(GetType(ReversiForm))
            Me.BW = New System.ComponentModel.BackgroundWorker
            ' Support ReportProgress to change the UI in the Main Thread
            BW.WorkerReportsProgress = True
            ' Support Cancellation to Cancel BW
            BW.WorkerSupportsCancellation = True
            Me.infoPanel = New System.Windows.Forms.Panel()
            Me.currentColorPanel = New System.Windows.Forms.Panel()
            Me.whiteCountLabel = New System.Windows.Forms.Label()
            Me.whiteTextLabel = New System.Windows.Forms.Label()
            Me.currentColorTextLabel = New System.Windows.Forms.Label()
            Me.blackCountLabel = New System.Windows.Forms.Label()
            Me.blackTextLabel = New System.Windows.Forms.Label()
            Me.moveListView = New System.Windows.Forms.ListView()
            Me.moveNullColumn = New System.Windows.Forms.ColumnHeader()
            Me.moveNumberColumn = New System.Windows.Forms.ColumnHeader()
            Me.movePlayerColumn = New System.Windows.Forms.ColumnHeader()
            Me.movePositionColumn = New System.Windows.Forms.ColumnHeader()
            Me.squaresPanel = New System.Windows.Forms.Panel()
            Me.mainMenu = New System.Windows.Forms.MainMenu()
            Me.gameMenuItem = New System.Windows.Forms.MenuItem()
            Me.newGameMenuItem = New System.Windows.Forms.MenuItem()
            Me.joinGameMenuItem = New System.Windows.Forms.MenuItem()
            Me.resignGameMenuItem = New System.Windows.Forms.MenuItem()
            Me.gameSeparator1MenuItem = New System.Windows.Forms.MenuItem()
            Me.optionsMenuItem = New System.Windows.Forms.MenuItem()
            Me.statisticsMenuItem = New System.Windows.Forms.MenuItem()
            Me.gameSeparator2MenuItem = New System.Windows.Forms.MenuItem()
            Me.exitMenuItem = New System.Windows.Forms.MenuItem()
            Me.helpMenuItem = New System.Windows.Forms.MenuItem()
            Me.helpTopicsMenuItem = New System.Windows.Forms.MenuItem()
            Me.helpSeparatorMenuItem = New System.Windows.Forms.MenuItem()
            Me.aboutMenuItem = New System.Windows.Forms.MenuItem()
            Me.boardPanel = New System.Windows.Forms.Panel()
            Me.cornerLabel = New System.Windows.Forms.Label()
            Me.statusProgressBar = New System.Windows.Forms.ProgressBar()
            Me.statusLabel = New System.Windows.Forms.Label()
            Me.statusPanel = New System.Windows.Forms.Panel()
            Me.playToolBar = New System.Windows.Forms.ToolBar()
            Me.newGameToolBarButton = New System.Windows.Forms.ToolBarButton()
            Me.resignGameToolBarButton = New System.Windows.Forms.ToolBarButton()
            Me.separatorToolBarButton = New System.Windows.Forms.ToolBarButton()
            Me.playImageList = New System.Windows.Forms.ImageList(Me.components)
            Me.infoPanel.SuspendLayout()
            Me.boardPanel.SuspendLayout()
            Me.statusPanel.SuspendLayout()
            Me.SuspendLayout()
            ' 
            ' infoPanel
            ' 
            Me.infoPanel.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
            Me.infoPanel.Controls.Add(Me.currentColorPanel)
            Me.infoPanel.Controls.Add(Me.whiteCountLabel)
            Me.infoPanel.Controls.Add(Me.whiteTextLabel)
            Me.infoPanel.Controls.Add(Me.currentColorTextLabel)
            Me.infoPanel.Controls.Add(Me.blackCountLabel)
            Me.infoPanel.Controls.Add(Me.blackTextLabel)
            Me.infoPanel.Controls.Add(Me.moveListView)
            Me.infoPanel.Location = New System.Drawing.Point(296, 32)
            Me.infoPanel.Name = "infoPanel"
            Me.infoPanel.Size = New System.Drawing.Size(168, 276)
            Me.infoPanel.TabIndex = 3
            ' 
            ' currentColorPanel
            ' 
            Me.currentColorPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
            Me.currentColorPanel.Location = New System.Drawing.Point(88, 56)
            Me.currentColorPanel.Name = "currentColorPanel"
            Me.currentColorPanel.Size = New System.Drawing.Size(16, 16)
            Me.currentColorPanel.TabIndex = 5
            Me.currentColorPanel.Visible = False
            ' 
            ' whiteCountLabel
            ' 
            Me.whiteCountLabel.Location = New System.Drawing.Point(80, 32)
            Me.whiteCountLabel.Name = "whiteCountLabel"
            Me.whiteCountLabel.Size = New System.Drawing.Size(24, 13)
            Me.whiteCountLabel.TabIndex = 3
            Me.whiteCountLabel.Text = "0"
            Me.whiteCountLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight
            ' 
            ' whiteTextLabel
            ' 
            Me.whiteTextLabel.AutoSize = True
            Me.whiteTextLabel.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CByte(0))
            Me.whiteTextLabel.Location = New System.Drawing.Point(40, 32)
            Me.whiteTextLabel.Name = "whiteTextLabel"
            Me.whiteTextLabel.Size = New System.Drawing.Size(39, 16)
            Me.whiteTextLabel.TabIndex = 2
            Me.whiteTextLabel.Text = "White: "
            ' 
            ' currentColorTextLabel
            ' 
            Me.currentColorTextLabel.AutoSize = True
            Me.currentColorTextLabel.Location = New System.Drawing.Point(32, 56)
            Me.currentColorTextLabel.Name = "currentColorTextLabel"
            Me.currentColorTextLabel.Size = New System.Drawing.Size(48, 16)
            Me.currentColorTextLabel.TabIndex = 4
            Me.currentColorTextLabel.Text = "Current: "
            Me.currentColorTextLabel.Visible = False
            ' 
            ' blackCountLabel
            ' 
            Me.blackCountLabel.Location = New System.Drawing.Point(80, 8)
            Me.blackCountLabel.Name = "blackCountLabel"
            Me.blackCountLabel.Size = New System.Drawing.Size(24, 13)
            Me.blackCountLabel.TabIndex = 1
            Me.blackCountLabel.Text = "0"
            Me.blackCountLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight
            ' 
            ' blackTextLabel
            ' 
            Me.blackTextLabel.AutoSize = True
            Me.blackTextLabel.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CByte(0))
            Me.blackTextLabel.Location = New System.Drawing.Point(40, 8)
            Me.blackTextLabel.Name = "blackTextLabel"
            Me.blackTextLabel.Size = New System.Drawing.Size(38, 16)
            Me.blackTextLabel.TabIndex = 0
            Me.blackTextLabel.Text = "Black: "
            ' 
            ' moveListView
            ' 
            Me.moveListView.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
            Me.moveListView.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
            Me.moveListView.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.moveNullColumn, Me.moveNumberColumn, Me.movePlayerColumn, Me.movePositionColumn})
            Me.moveListView.FullRowSelect = True
            Me.moveListView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable
            Me.moveListView.Location = New System.Drawing.Point(2, 88)
            Me.moveListView.Name = "moveListView"
            Me.moveListView.Size = New System.Drawing.Size(164, 188)
            Me.moveListView.TabIndex = 6
            Me.moveListView.TabStop = False
            Me.moveListView.View = System.Windows.Forms.View.Details
            ' 
            ' moveNullColumn
            ' 
            Me.moveNullColumn.Text = ""
            Me.moveNullColumn.TextAlign = System.Windows.Forms.HorizontalAlignment.Right
            Me.moveNullColumn.Width = 0
            ' 
            ' moveNumberColumn
            ' 
            Me.moveNumberColumn.Text = "#"
            Me.moveNumberColumn.TextAlign = System.Windows.Forms.HorizontalAlignment.Right
            Me.moveNumberColumn.Width = 32
            ' 
            ' movePlayerColumn
            ' 
            Me.movePlayerColumn.Text = "Player"
            Me.movePlayerColumn.TextAlign = System.Windows.Forms.HorizontalAlignment.Right
            Me.movePlayerColumn.Width = 52
            ' 
            ' movePositionColumn
            ' 
            Me.movePositionColumn.Text = "Position"
            Me.movePositionColumn.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
            Me.movePositionColumn.Width = 62
            ' 
            ' squaresPanel
            ' 
            Me.squaresPanel.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
            Me.squaresPanel.Location = New System.Drawing.Point(16, 16)
            Me.squaresPanel.Name = "squaresPanel"
            Me.squaresPanel.Size = New System.Drawing.Size(256, 256)
            Me.squaresPanel.TabIndex = 1
            ' 
            ' mainMenu
            ' 
            Me.mainMenu.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.gameMenuItem, Me.helpMenuItem})
            ' 
            ' gameMenuItem
            ' 
            Me.gameMenuItem.Index = 0
            Me.gameMenuItem.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.newGameMenuItem, Me.joinGameMenuItem, Me.resignGameMenuItem, Me.gameSeparator1MenuItem, Me.optionsMenuItem, Me.statisticsMenuItem, Me.gameSeparator2MenuItem, _
             Me.exitMenuItem})
            Me.gameMenuItem.ShowShortcut = False
            Me.gameMenuItem.Text = "&Game"
            ' 
            ' newGameMenuItem
            ' 
            Me.newGameMenuItem.Index = 0
            Me.newGameMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlN
            Me.newGameMenuItem.Text = "&New Game"
            AddHandler Me.newGameMenuItem.Click, New System.EventHandler(AddressOf Me.newGameMenuItem_Click)
            ' 
            ' joinGameMenuItem
            ' 
            Me.joinGameMenuItem.Index = 1
            Me.joinGameMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlJ
            Me.joinGameMenuItem.Text = "&Join Game"
            AddHandler Me.joinGameMenuItem.Click, New System.EventHandler(AddressOf Me.joinGameMenuItem_Click)
            ' 
            ' resignGameMenuItem
            ' 
            Me.resignGameMenuItem.Enabled = False
            Me.resignGameMenuItem.Index = 2
            Me.resignGameMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlR
            Me.resignGameMenuItem.Text = "&Resign Game"
            AddHandler Me.resignGameMenuItem.Click, New System.EventHandler(AddressOf Me.resignGameMenuItem_Click)
            ' 
            ' gameSeparator1MenuItem
            ' 
            Me.gameSeparator1MenuItem.Index = 3
            Me.gameSeparator1MenuItem.Text = "-"
            ' 
            ' optionsMenuItem
            ' 
            Me.optionsMenuItem.Index = 4
            Me.optionsMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlO
            Me.optionsMenuItem.Text = "&Options..."
            AddHandler Me.optionsMenuItem.Click, New System.EventHandler(AddressOf Me.optionsMenuItem_Click)
            ' 
            ' statisticsMenuItem
            ' 
            Me.statisticsMenuItem.Index = 5
            Me.statisticsMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlS
            Me.statisticsMenuItem.Text = "&Statistics..."
            AddHandler Me.statisticsMenuItem.Click, New System.EventHandler(AddressOf Me.statisticsMenuItem_Click)
            ' 
            ' gameSeparator2MenuItem
            ' 
            Me.gameSeparator2MenuItem.Index = 6
            Me.gameSeparator2MenuItem.Text = "-"
            ' 
            ' exitMenuItem
            ' 
            Me.exitMenuItem.Index = 7
            Me.exitMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlX
            Me.exitMenuItem.Text = "&Exit"
            AddHandler Me.exitMenuItem.Click, New System.EventHandler(AddressOf Me.exitMenuItem_Click)
            ' 
            ' helpMenuItem
            ' 
            Me.helpMenuItem.Index = 1
            Me.helpMenuItem.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.aboutMenuItem})
            Me.helpMenuItem.ShowShortcut = False
            Me.helpMenuItem.Text = "&Help"
            ' 
            ' aboutMenuItem
            ' 
            Me.aboutMenuItem.Index = 0
            Me.aboutMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlA
            Me.aboutMenuItem.Text = "&About"
            AddHandler Me.aboutMenuItem.Click, New System.EventHandler(AddressOf Me.aboutMenuItem_Click)
            ' 
            ' boardPanel
            ' 
            Me.boardPanel.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
            Me.boardPanel.BackColor = System.Drawing.SystemColors.Control
            Me.boardPanel.Controls.Add(Me.cornerLabel)
            Me.boardPanel.Controls.Add(Me.squaresPanel)
            Me.boardPanel.Location = New System.Drawing.Point(8, 32)
            Me.boardPanel.Name = "boardPanel"
            Me.boardPanel.Size = New System.Drawing.Size(272, 272)
            Me.boardPanel.TabIndex = 2
            ' 
            ' cornerLabel
            ' 
            Me.cornerLabel.BackColor = System.Drawing.SystemColors.ControlDark
            Me.cornerLabel.ForeColor = System.Drawing.SystemColors.ControlLightLight
            Me.cornerLabel.Location = New System.Drawing.Point(0, 0)
            Me.cornerLabel.Name = "cornerLabel"
            Me.cornerLabel.Size = New System.Drawing.Size(16, 16)
            Me.cornerLabel.TabIndex = 0
            ' 
            ' statusProgressBar
            ' 
            Me.statusProgressBar.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
            Me.statusProgressBar.BackColor = System.Drawing.SystemColors.ControlLight
            Me.statusProgressBar.Location = New System.Drawing.Point(350, 2)
            Me.statusProgressBar.Name = "statusProgressBar"
            Me.statusProgressBar.Size = New System.Drawing.Size(104, 16)
            Me.statusProgressBar.[Step] = 1
            Me.statusProgressBar.TabIndex = 1
            Me.statusProgressBar.Visible = False
            ' 
            ' statusLabel
            ' 
            Me.statusLabel.AutoSize = True
            Me.statusLabel.Location = New System.Drawing.Point(16, 2)
            Me.statusLabel.Name = "statusLabel"
            Me.statusLabel.Size = New System.Drawing.Size(0, 16)
            Me.statusLabel.TabIndex = 0
            Me.statusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
            ' 
            ' statusPanel
            ' 
            Me.statusPanel.Anchor = CType(((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
            Me.statusPanel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
            Me.statusPanel.Controls.Add(Me.statusProgressBar)
            Me.statusPanel.Controls.Add(Me.statusLabel)
            Me.statusPanel.Location = New System.Drawing.Point(8, 312)
            Me.statusPanel.Name = "statusPanel"
            Me.statusPanel.Size = New System.Drawing.Size(456, 24)
            Me.statusPanel.TabIndex = 4
            ' 
            ' playToolBar
            ' 
            Me.playToolBar.Buttons.AddRange(New System.Windows.Forms.ToolBarButton() {Me.newGameToolBarButton, Me.resignGameToolBarButton})
            Me.playToolBar.Divider = False
            Me.playToolBar.DropDownArrows = True
            Me.playToolBar.ImageList = Me.playImageList
            Me.playToolBar.Location = New System.Drawing.Point(0, 0)
            Me.playToolBar.Name = "playToolBar"
            Me.playToolBar.ShowToolTips = True
            Me.playToolBar.Size = New System.Drawing.Size(472, 26)
            Me.playToolBar.TabIndex = 1
            AddHandler Me.playToolBar.ButtonClick, New System.Windows.Forms.ToolBarButtonClickEventHandler(AddressOf Me.playToolBar_ButtonClick)
            ' 
            ' newGameToolBarButton
            ' 
            Me.newGameToolBarButton.ImageIndex = 0
            Me.newGameToolBarButton.ToolTipText = "New Game"
            ' 
            ' resignGameToolBarButton
            ' 
            Me.resignGameToolBarButton.Enabled = False
            Me.resignGameToolBarButton.ImageIndex = 1
            Me.resignGameToolBarButton.ToolTipText = "Resign Game"
            ' 
            ' playImageList
            ' 
            Me.playImageList.ImageSize = New System.Drawing.Size(16, 16)
            Me.playImageList.ImageStream = DirectCast(resources.GetObject("playImageList.ImageStream"), System.Windows.Forms.ImageListStreamer)
            Me.playImageList.TransparentColor = System.Drawing.Color.Transparent
            ' 
            ' ReversiForm
            ' 
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.ClientSize = New System.Drawing.Size(472, 345)
            Me.Controls.Add(Me.playToolBar)
            Me.Controls.Add(Me.boardPanel)
            Me.Controls.Add(Me.infoPanel)
            Me.Controls.Add(Me.statusPanel)
            Me.Icon = DirectCast(resources.GetObject("$this.Icon"), System.Drawing.Icon)
            Me.KeyPreview = True
            Me.Menu = Me.mainMenu
            Me.Name = "OthelloForm"
            Me.Text = "Othello"
            AddHandler Me.Resize, New System.EventHandler(AddressOf Me.ReversiForm_Resize)
            AddHandler Me.Closing, New System.ComponentModel.CancelEventHandler(AddressOf Me.ReversiForm_Closing)
            AddHandler Me.KeyPress, New System.Windows.Forms.KeyPressEventHandler(AddressOf Me.ReversiForm_KeyPress)
            AddHandler Me.Move, New System.EventHandler(AddressOf Me.ReversiForm_Move)
            AddHandler Me.Closed, New System.EventHandler(AddressOf Me.ReversiForm_Closed)
            Me.infoPanel.ResumeLayout(False)
            Me.boardPanel.ResumeLayout(False)
            Me.statusPanel.ResumeLayout(False)
            Me.ResumeLayout(False)

        End Sub
#End Region

        ''' <summary>
        ''' The main entry point for the application.
        ''' </summary>
        <STAThread()> _
        Private Shared Sub Main()
            Application.Run(New ReversiForm())
        End Sub

        ' ===================================================================
        ' This code handles game play.
        ' ===================================================================
        '
        ' Starts a new game or, optionally, restarts an ended game.
        '
        Private Sub StartGame()
            ' Enable/disable the menu items and tool bar buttons as
            ' appropriate.
            Me.newGameMenuItem.Enabled = InlineAssignHelper(Me.playToolBar.Buttons(CInt(ReversiForm.ToolBarButton.NewGame)).Enabled, False)
            Me.resignGameMenuItem.Enabled = InlineAssignHelper(Me.playToolBar.Buttons(CInt(ReversiForm.ToolBarButton.ResignGame)).Enabled, True)

            ' Initialize the information display.
            Me.currentColorTextLabel.Visible = True
            Me.currentColorPanel.Visible = True

            ' Initialize a new game.
            ' Initialize the move list.
            Me.moveNumber = 1
            Me.moveListView.Items.Clear()
            Me.moveListView.Refresh()

            ' Initialize the move history.
            Me.moveHistory = New ArrayList(60)

            ' Initialize the last move color.
            Me.lastMoveColor = board.Empty

            ' Initialize the board.
            Me.board.SetForNewGame()
            Me.UpdateBoardDisplay()

            ' Initialize the status display.
            Me.statusLabel.Text = ""
            Me.statusPanel.Refresh()

            ' Set the first player.
            Me.currentColor = Me.options.FirstMove

            ' Start the first turn.
            Me.StartTurn()
        End Sub

        '
        ' Ends the current game.
        '
        Private Sub EndGame()
            Me.EndGame(False)
        End Sub

        '
        ' Ends the current game, optionally by player resignation.
        '
        Private Sub EndGame(ByVal isResignation As Boolean)
            ' Set the game state.
            Me.gameState = GameStates.GameOver

            ' Enable/disable the menu items and tool bar buttons as
            ' appropriate.
            Me.newGameMenuItem.Enabled = InlineAssignHelper(Me.playToolBar.Buttons(CInt(ReversiForm.ToolBarButton.NewGame)).Enabled, True)
            Me.resignGameMenuItem.Enabled = InlineAssignHelper(Me.playToolBar.Buttons(CInt(ReversiForm.ToolBarButton.ResignGame)).Enabled, False)
            Me.joinGameMenuItem.Enabled = True

            ' Clear the current player indicator display.
            Me.currentColorTextLabel.Visible = False
            Me.currentColorPanel.BackColor = Color.Empty
            Me.currentColorPanel.Visible = False

            ' Hide the status progress bar.
            Me.statusProgressBar.Visible = False
            Me.statusPanel.Refresh()

            '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!(isos na tn xreiastoume)
            '  Dim userColor As Integer = board.Empty

            ' Save the current statistics, in case the game is restarted.
            Me.oldStatistics = New Statistics(Me.statistics)

            ' Handle a resignation.
            If isResignation Then
                ' Update the status message and record the game as a 64-0
                ' loss for the resigning player.
                If iam_server Then
                    resigningColor = Color.Black.ToArgb()
                    Me.statusLabel.Text = "Black resigns."
                    Me.statistics.Update(0, 64, Color.White.ToArgb(), resigningColor)
                Else
                    resigningColor = Color.White.ToArgb()
                    Me.statusLabel.Text = "White resigns."
                    Me.statistics.Update(64, 0, Color.Black.ToArgb(), resigningColor)
                End If
            Else
                ' Handle an end game.
                ' Update the status message.
                If Me.board.BlackCount > Me.board.WhiteCount Then
                    Me.statusLabel.Text = "Black wins."
                ElseIf Me.board.WhiteCount > Me.board.BlackCount Then
                    Me.statusLabel.Text = "White wins."
                Else
                    Me.statusLabel.Text = "Draw."
                End If

                ' Record the result.!!!!!!!!(to current color tha antikatastathei+isos xreiastei allagi stin statistics)
                Me.statistics.Update(Me.board.BlackCount, Me.board.WhiteCount, Me.currentColor, Me.currentColor)
            End If

            'gameAdapter.DeleteGameRecord(serverLocalIP.ToString)
            ' Update the status display.
            Me.statusPanel.Refresh()

            ' Re-enable the undo move-related menu items and tool bar
            ' buttons.
        End Sub

        '
        ' Sets up for the current player to make a move or ends the game if
        ' neither player can make a valid move.
        '
        Private Sub StartTurn()
            ' If the current player cannot make a valid move, forfeit the turn.
            If Not Me.board.HasAnyValidMove(Me.currentColor) Then
                ' Switch back to the other player.
                Me.currentColor *= -1

                ' If the original player cannot make a valid move either, the game is over.
                If Not Me.board.HasAnyValidMove(Me.currentColor) Then
                    Me.EndGame()
                    Return
                End If
            End If

            ' Set the player text for the status display.
            Dim playerText As String = [String].Format("{0}'s", (If(Me.currentColor = board.Black, "Black", "White")))

            ' Update the turn display.
            If Me.currentColor = board.Black Then
                Me.currentColorPanel.BackColor = Color.Black
            Else
                Me.currentColorPanel.BackColor = Color.White
            End If
            Me.currentColorPanel.Refresh()

            ' set up for a user move.
            ' Set the game state.
            Me.gameState = GameStates.InPlayerMove

            ' Reset the keyed column and row numbers.
            Me.keyedColNumber = -1
            Me.keyedRowNumber = -1

            ' Show valid moves, if that option is active.
            If Me.options.ShowValidMoves Then
                Me.HighlightValidMoves()
                Me.squaresPanel.Refresh()
            End If

            ' Update the status display.
            Me.statusLabel.Text = [String].Format("{0} move...", playerText)
            Me.statusProgressBar.Visible = False

            ' Set focus on the form so it will receive key presses.
            Me.Focus()

            ' Update the status display.
            Me.statusPanel.Refresh()
        End Sub
        ' Variables for Socket connection
        Dim server As TcpListener
        Dim client As TcpClient
        Dim connection As Socket
        Dim s_stream As NetworkStream
        Dim s_reader As BinaryReader
        Dim s_writer As BinaryWriter
        Dim rowSend As Integer
        Dim colSend As Integer
        Dim waiting As Boolean

        ' Get Local IP address for Socket
        Dim myhost As String = Dns.GetHostName()
        Dim myip As String = Dns.GetHostAddresses(myhost).GetValue(2).ToString()

        Dim serverLocalIP As IPAddress = IPAddress.Parse(myip)
        Dim iam_server = False
        Dim resigningColor As Integer

        ' Database Variables
        Dim givenName As String
        Dim givenPassword As String
        Dim givenNetType As String

        Dim dataset As New OthelloDB
        Dim gameAdapter As New OthelloDBTableAdapters.gameTableTableAdapter
        Dim userAdapter As New OthelloDBTableAdapters.userTableTableAdapter
        Dim adapterManager As New OthelloDBTableAdapters.TableAdapterManager



        Dim connected As Boolean = False
        '
        ' Sends a move to the distant player
        '
        Private Sub MakeDistantMove(ByVal receivedRow As Integer, ByVal receivedCol As Integer)
            MakePlayerMove(receivedRow, receivedCol)
        End Sub
        '
        ' Makes a move for the current player.
        '
        Private Sub MakeMove(ByVal row As Integer, ByVal col As Integer)
            ' Clean up the move history to ensure that it contains only the
            ' moves made prior to this one.

            While Me.moveHistory.Count > Me.moveNumber - 1
                Me.moveHistory.RemoveAt(Me.moveHistory.Count - 1)
            End While

            ' Add the move to the move list.
            Dim color As String = "Black"
            If Me.currentColor = board.White Then
                color = "White"
            End If
            Dim subItems As String() = {[String].Empty, Me.moveNumber.ToString(), color, (alpha(col) & (row + 1).ToString())}
            Dim listItem As New ListViewItem(subItems)
            Me.moveListView.Items.Add(listItem)

            ' Scroll Bar if necessary for the listview
            Me.moveListView.EnsureVisible(Me.moveListView.Items.Count - 1)

            ' Add the move to the moveHistory
            Me.moveHistory.Add(New MoveRecord(Me.board, Me.currentColor, listItem))

            ' Bump the move number.
            Me.moveNumber += 1

            ' Update the status display.
            Me.statusLabel.Text = ""
            Me.statusProgressBar.Visible = False
            Me.statusPanel.Refresh()

            ' Clear any board square highlighting.
            Me.UnHighlightSquares()

            ' Make a copy of the board (for doing move animation).
            Dim oldBoard As New Board(Me.board)

            ' Make the move on the board.
            Me.board.MakeMove(Me.currentColor, row, col)

            ' Update the display to reflect the board changes.
            Me.UpdateBoardDisplay()

            ' Save the player color.
            Me.lastMoveColor = Me.currentColor

            ' End the move.
            Me.EndMove()
        End Sub

        '
        ' Called when a move has been completed (including any animation) to
        ' start the next turn.
        '
        Private Sub EndMove()
            ' Set the game state.
            Me.gameState = GameStates.MoveCompleted

            ' Switch players and start the next turn.
            Me.currentColor *= -1
            Me.StartTurn()
        End Sub

        '
        ' Makes a player-controlled move for the current color.
        '
        Private Sub MakePlayerMove(ByVal row As Integer, ByVal col As Integer)
            ' Make the move.
            Me.MakeMove(row, col)
        End Sub

        '
        ' Define delegates for callbacks from the worker thread.
        '
        Public Delegate Sub UpdateStatusProgressDelegate()

        '
        ' Updates the status progress bar.
        ' Note: Called from the worker thread.
        '
        Private Sub UpdateStatusProgress()
            ' Increase the progress bar value by one.
            If Me.statusProgressBar.Value < Me.statusProgressBar.Maximum Then
                Me.statusProgressBar.Value += 1
                Me.statusProgressBar.Refresh()
            End If
        End Sub
        ' ===================================================================
        ' Code to handle the board display.
        ' ===================================================================

        '
        ' Updates the display to reflect the current game board.
        '
        Private Sub UpdateBoardDisplay()
            ' Set counts.
            Me.blackCountLabel.Text = Me.board.BlackCount.ToString()
            Me.blackCountLabel.Refresh()
            Me.whiteCountLabel.Text = Me.board.WhiteCount.ToString()
            'Me.whiteCountLabel.Refresh()

            ' Map the current game board to the square controls.
            Dim squareControl As SquareControl
            Dim i As Integer, j As Integer
            For i = 0 To 7
                For j = 0 To 7
                    squareControl = DirectCast(Me.squaresPanel.Controls(i * 8 + j), SquareControl)
                    squareControl.Contents = Me.board.GetSquareContents(i, j)
                    squareControl.PreviewContents = board.Empty
                Next
            Next

            ' Redraw the board.
            Me.squaresPanel.Refresh()
        End Sub

        '
        ' Highlights the board squares that represent valid moves for the
        ' current player.
        '
        Private Sub HighlightValidMoves()
            ' Check each square.
            Dim squareControl As SquareControl
            Dim i As Integer, j As Integer
            For i = 0 To 7
                For j = 0 To 7
                    squareControl = DirectCast(Me.squaresPanel.Controls(i * 8 + j), SquareControl)
                    If Me.board.IsValidMove(Me.currentColor, i, j) Then
                        squareControl.IsValid = True
                    Else
                        squareControl.IsValid = False
                    End If
                Next
            Next
        End Sub

        '
        ' Removes any highlighting from all the board squares.
        '
        Private Sub UnHighlightSquares()
            ' Clear the flags on each square.
            Dim squareControl As SquareControl
            Dim i As Integer, j As Integer
            For i = 0 To 7
                For j = 0 To 7
                    squareControl = DirectCast(Me.squaresPanel.Controls(i * 8 + j), SquareControl)
                    squareControl.IsActive = False
                    squareControl.IsValid = False
                    squareControl.IsNew = False
                Next
            Next
        End Sub

        '
        ' Sets the board square colors based on the current game options.
        '
        Private Sub SetSquareControlColors()
            SquareControl.ActiveSquareBackColor = Me.options.ActiveSquareColor
            SquareControl.NormalBackColor = Me.options.BoardColor
            SquareControl.MoveIndicatorColor = Me.options.MoveIndicatorColor
            SquareControl.ValidMoveBackColor = Me.options.ValidMoveColor
        End Sub

        '====================================================================
        ' These functions to handle the loading and saving of the program
        ' settings.
        '====================================================================

        '
        ' Loads any saved program settings.
        '
        Private Sub LoadProgramSettings()
            ' Load the saved window settings and resize the window.
            Try
                ' Load the saved window settings.
                Dim left As Integer = System.Int32.Parse(Me.settings.GetValue("Window", "Left"))
                Dim top As Integer = System.Int32.Parse(Me.settings.GetValue("Window", "Top"))
                Dim width As Integer = System.Int32.Parse(Me.settings.GetValue("Window", "Width"))
                Dim height As Integer = System.Int32.Parse(Me.settings.GetValue("Window", "Height"))

                ' Reposition and resize the window.
                Me.StartPosition = System.Windows.Forms.FormStartPosition.Manual
                Me.DesktopLocation = New Point(left, top)
                Me.ClientSize = New Size(width, height)

                ' Load saved options.
                Me.options.ShowValidMoves = CBool(System.[Boolean].Parse(Me.settings.GetValue("Options", "ShowValidMoves")))
                Me.options.PreviewMoves = CBool(System.[Boolean].Parse(Me.settings.GetValue("Options", "PreviewMoves")))
                Me.options.BoardColor = Color.FromArgb(System.Int32.Parse(Me.settings.GetValue("Options", "BoardColor")))
                Me.options.ValidMoveColor = Color.FromArgb(System.Int32.Parse(Me.settings.GetValue("Options", "ValidMoveColor")))
                Me.options.ActiveSquareColor = Color.FromArgb(System.Int32.Parse(Me.settings.GetValue("Options", "ActiveSquareColor")))
                Me.options.MoveIndicatorColor = Color.FromArgb(System.Int32.Parse(Me.settings.GetValue("Options", "MoveIndicatorColor")))
                Me.options.FirstMove = CInt(System.Int32.Parse(Me.settings.GetValue("Options", "FirstMove")))

                ' Set the square control colors based on options loaded.
                Me.SetSquareControlColors()

                ' Load saved statistics.
                Me.statistics.BlackWins = System.Int32.Parse(settings.GetValue("Statistics", "BlackWins"))
                Me.statistics.WhiteWins = System.Int32.Parse(settings.GetValue("Statistics", "WhiteWins"))
                Me.statistics.OverallDraws = System.Int32.Parse(settings.GetValue("Statistics", "OverallDraws"))
                Me.statistics.BlackTotalScore = System.Int32.Parse(settings.GetValue("Statistics", "BlackTotalScore"))
                Me.statistics.WhiteTotalScore = System.Int32.Parse(settings.GetValue("Statistics", "WhiteTotalScore"))
                Me.statistics.ComputerWins = System.Int32.Parse(settings.GetValue("Statistics", "ComputerWins"))
                Me.statistics.UserWins = System.Int32.Parse(settings.GetValue("Statistics", "UserWins"))
                Me.statistics.VsComputerDraws = System.Int32.Parse(settings.GetValue("Statistics", "VsComputerDraws"))
                Me.statistics.ComputerTotalScore = System.Int32.Parse(settings.GetValue("Statistics", "ComputerTotalScore"))
                Me.statistics.UserTotalScore = System.Int32.Parse(settings.GetValue("Statistics", "UserTotalScore"))
            Catch ex As Exception
            End Try
        End Sub

        '
        ' Saves the current program settings.
        '
        Private Sub SaveProgramSettings()
            ' Save window settings.
            Me.settings.SetValue("Window", "Left", Me.windowSettings.Left.ToString())
            Me.settings.SetValue("Window", "Top", Me.windowSettings.Top.ToString())
            Me.settings.SetValue("Window", "Width", Me.windowSettings.Width.ToString())
            Me.settings.SetValue("Window", "Height", Me.windowSettings.Height.ToString())

            ' Save game options.
            Me.settings.SetValue("Options", "ShowValidMoves", Me.options.ShowValidMoves.ToString())
            Me.settings.SetValue("Options", "PreviewMoves", Me.options.PreviewMoves.ToString())
            Me.settings.SetValue("Options", "BoardColor", SquareControl.NormalBackColor.ToArgb().ToString())
            Me.settings.SetValue("Options", "ValidMoveColor", SquareControl.ValidMoveBackColor.ToArgb().ToString())
            Me.settings.SetValue("Options", "ActiveSquareColor", SquareControl.ActiveSquareBackColor.ToArgb().ToString())
            Me.settings.SetValue("Options", "MoveIndicatorColor", SquareControl.MoveIndicatorColor.ToArgb().ToString())
            Me.settings.SetValue("Options", "FirstMove", Me.options.FirstMove.ToString())

            ' Save statistics.
            Me.settings.SetValue("Statistics", "BlackWins", Me.statistics.BlackWins.ToString())
            Me.settings.SetValue("Statistics", "WhiteWins", Me.statistics.WhiteWins.ToString())
            Me.settings.SetValue("Statistics", "OverallDraws", Me.statistics.OverallDraws.ToString())
            Me.settings.SetValue("Statistics", "BlackTotalScore", Me.statistics.BlackTotalScore.ToString())
            Me.settings.SetValue("Statistics", "WhiteTotalScore", Me.statistics.WhiteTotalScore.ToString())
            Me.settings.SetValue("Statistics", "ComputerWins", Me.statistics.ComputerWins.ToString())
            Me.settings.SetValue("Statistics", "UserWins", Me.statistics.UserWins.ToString())
            Me.settings.SetValue("Statistics", "VsComputerDraws", Me.statistics.VsComputerDraws.ToString())
            Me.settings.SetValue("Statistics", "ComputerTotalScore", Me.statistics.ComputerTotalScore.ToString())
            Me.settings.SetValue("Statistics", "UserTotalScore", Me.statistics.UserTotalScore.ToString())

            ' Save the program settings.
            Me.settings.Save()
        End Sub

        '====================================================================
        ' Event handlers for the form.
        '====================================================================

        '
        ' Handles a window close.
        '
        Private Sub ReversiForm_Closed(ByVal sender As Object, ByVal e As System.EventArgs)
            ' Stop the computer move thread, if active.

            ' Save the current program settings.
            Me.SaveProgramSettings()
        End Sub

        '
        ' Handles a window close request. If a game is active, it will prompt
        ' for confirmation first.
        '
        Private Sub ReversiForm_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
            Dim doClose As Boolean = True

            ' Prompt for confirmation if a game is in progress.
            If Me.gameState <> GameStates.GameOver Then
                ' Create and show the confirm dialog, saving the result.
                Dim dlg As New ConfirmDialog("Are you sure you want to close the game?")
                If dlg.ShowDialog(Me) <> DialogResult.Yes Then
                    doClose = False
                Else
                    ' Call method to close the connection
                    close_connection()
                End If
                dlg.Dispose()
            End If

            ' Cancel the close request if necessary.
            If Not doClose Then
                e.Cancel = True
            End If
        End Sub

        '
        ' Handles a key press.
        '
        Private Sub ReversiForm_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
            ' Check the game state to ensure it is the user's turn.
            If Me.gameState <> GameStates.InPlayerMove Then
                Return
            End If

            ' Convert the key character to column/row number.
            Dim s As String = e.KeyChar.ToString().ToUpper()
            Dim col As Integer = ReversiForm.alpha.IndexOf(s)
            Dim row As Integer
            Try
                row = System.Int32.Parse(s) - 1
            Catch
                row = -1
            End Try

            ' Is the key a valid column letter?
            If col >= 0 AndAlso col < 8 Then
                ' Yes; store it, clear the keyed row number and exit.
                Me.keyedColNumber = col
                Me.keyedRowNumber = -1
                Return
            End If

            ' If we don't have a valid column number yet, exit.
            If Me.keyedColNumber < 0 OrElse Me.keyedColNumber > 7 Then
                Return
            End If

            ' We have a valid column number. Is the key a valid row number?
            If row < 0 OrElse row > 7 Then
                ' No, reset both and exit.
                Me.keyedColNumber = -1
                Me.keyedRowNumber = -1
                Return
            Else
                Me.keyedRowNumber = row
            End If

            ' The keyed column and row numbers are valid. Is the position a
            ' valid move?
            If Me.board.IsValidMove(Me.currentColor, Me.keyedRowNumber, Me.keyedColNumber) Then
                ' Yes, make it.
                Me.MakePlayerMove(Me.keyedRowNumber, Me.keyedColNumber)
            Else
                ' No, reset both.
                Me.keyedColNumber = -1
                Me.keyedRowNumber = -1
            End If
        End Sub

        '
        ' Handles a window move.
        '
        Private Sub ReversiForm_Move(ByVal sender As Object, ByVal e As System.EventArgs)
            ' If the window has not been minimized or maximized, save its location.
            If Me.WindowState = FormWindowState.Normal Then
                Me.windowSettings.X = Me.DesktopLocation.X
                Me.windowSettings.Y = Me.DesktopLocation.Y
            End If
        End Sub

        '
        ' Handles a window resize.
        '
        Private Sub ReversiForm_Resize(ByVal sender As Object, ByVal e As System.EventArgs)
            ' Determine the size each square should be within the board.
            Dim l As Integer = CInt(Math.Min(Me.squaresPanel.Width, Me.squaresPanel.Height) \ 8)
            l = Math.Max(l, 8)

            ' Resize and reposition each square control.
            Dim i As Integer, j As Integer
            For i = 0 To 7
                For j = 0 To 7
                    Me.squareControls(i, j).Width = l
                    Me.squareControls(i, j).Height = l
                    Me.squareControls(i, j).Left = j * l
                    Me.squareControls(i, j).Top = i * l
                Next
            Next

            ' Fix the column and row headers.
            For i = 0 To 7
                Me.colLabels(i).Width = l
                Me.colLabels(i).Left = Me.cornerLabel.Width + i * l
                Me.rowLabels(i).Height = l
                Me.rowLabels(i).Top = Me.cornerLabel.Height + i * l
            Next

            ' Fix the info panel height to align it's bottom with the bottom row of squares.
            Me.infoPanel.Height = 8 * l + Me.colLabels(0).Height

            ' Position the progress bar just to the right of the satus text.
            Me.statusProgressBar.Left = Me.statusLabel.Left + Me.statusLabel.Width

            ' If the window has not been minimized or maximized, save it size.
            If Me.WindowState = FormWindowState.Normal Then
                Me.windowSettings.Width = Me.ClientSize.Width
                Me.windowSettings.Height = Me.ClientSize.Height
            End If
        End Sub

        '====================================================================
        ' Event handlers for the menu items.
        '====================================================================

        '
        ' Handles a "New Game" click.
        '
        Private Sub newGameMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            ' Start a new game.
            If LoginDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
                givenName = LoginDialog.usernameTextBox.Text
                givenPassword = LoginDialog.passwordTextBox.Text
                givenNetType = LoginDialog.NetTypeCombo.SelectedItem.ToString
                If Not connected Then
                    Me.StartGame()
                    iam_server = True
                    BW.RunWorkerAsync()
                    joinGameMenuItem.Enabled = False
                End If
            End If
        End Sub
        Private Sub BW_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BW.DoWork
            If Not connected Then
                do_connect()
            End If
            Dim receivedRow As Integer
            Dim receivedCol As Integer
            Do
                receivedRow = -1
                receivedCol = -1
                Try
                    receivedRow = s_reader.ReadInt32()
                    receivedCol = s_reader.ReadInt32()
                    If Me.InvokeRequired Then
                        Dim s As New MakeDistantMoveCallback(AddressOf MakeDistantMove)
                        Me.Invoke(s, New Object() {receivedRow, receivedCol})
                        waiting = False
                    Else

                        MakePlayerMove(receivedRow, receivedCol)
                    End If
                Catch ex As Exception
                    close_connection()
                    'Catch ex As
                End Try

            Loop While receivedRow <> -1 And receivedCol <> -1


            's_reader.Close()
            's_stream.Close()

        End Sub
        Delegate Sub MakeDistantMoveCallback(ByVal [receivedRow] As Integer, ByVal [receivedCol] As Integer)

        Private Sub myprinttext(ByVal nt As String)
            If Me.statusLabel.InvokeRequired Then
                ' It's on a different thread, so use Invoke.
                Dim d As New SetStatusTextCallback(AddressOf SetStatusText)
                Me.Invoke(d, New Object() {nt & vbCrLf})
            Else
                ' It's on the same thread, no need for Invoke.
                Me.statusLabel.Text = nt & vbCrLf
            End If
        End Sub
        Delegate Sub SetStatusTextCallback(ByVal [text] As String)

        Private Sub SetStatusText(ByVal text As String)
            statusLabel.Text = text
        End Sub
        ' DB Variables because we had problems with Dataset
        Dim connStr = "server=188.121.44.135;User Id=othellodb;password=othelloAde2012;database=othellodb2"
        Dim sqlConn As New MySqlConnection(connStr)
        Dim sqlReader As MySqlDataReader
        ' Variable to get localScore and Send it to DB
        Dim localScore As Integer
        Dim deleteGameRecord = "DELETE FROM gameTable WHERE(NumberOfPlayers = 2) AND (serverIP = " & serverLocalIP.ToString() & ")"
        Dim noOfPlayers = "UPDATE gameTable SET NumberOfPlayers = 2 WHERE(serverIP =" & serverLocalIP.ToString() & ")"
        Dim getUsernamePassword = "SELECT (userName, password) FROM userTable"
        Dim insertNewUser = "INSERT INTO userTable(userName, password, wins, score) VALUES(" & givenName & "," & givenPassword & ", 0, 0)"
        Dim updateLoserScore = "UPDATE userTable SET score = score + " & localScore & " WHERE (userName = " & givenName & ") AND (password = " & givenPassword & ")"
        Dim updateWinnerScore = "UPDATE userTable SET wins = wins + 1, score = score + " & localScore & "WHERE (userName = " & givenName & ") AND (password = " & givenPassword & ")"
        '   Handles a new connection"
        '
        Private Sub do_connect()
            If iam_server Then
                server = New TcpListener(serverLocalIP, 54321)
                server.Start()

                myprinttext("Waiting for other player...")
                'Try
                'sqlConn.Open()
                'Dim createGameRecord = "INSERT INTO gameTable(NumberOfPlayers, serverIP, NetType) VALUES(1," & serverLocalIP.ToString() & "," & givenNetType & ")"
                'Dim sqlCommand As New MySqlCommand(createGameRecord, connStr)
                'sqlCommand.Connection = sqlConn
                'sqlCommand.ExecuteNonQuery()
                'Catch ex As Exception
                'MsgBox(ex.Message)
                'End Try

                'sqlConn.Close()
                connection = server.AcceptSocket()

                s_stream = New NetworkStream(connection)

                myprinttext("Ready to play! It's your turn...")

                waiting = False
            Else
                'If Not connected Then
                client = New TcpClient()
                Dim hisIP As IPAddress
                'Try
                'Dim getFreeGameRecord = "SELECT serverIP FROM gameTable WHERE(NumberOfPlayers = 1) AND (ID IN(SELECT MIN(ID) AS Expr1 FROM gameTable g WHERE(NetType =" & givenNetType & "))) AND (NetType = " & givenNetType & ")"
                'Dim sqlCommand As New MySqlCommand(getFreeGameRecord, connStr)
                'sqlConn.Open()
                'sqlCommand.Connection = sqlConn
                'sqlReader = sqlCommand.ExecuteReader
                'While sqlReader.Read()
                myprinttext("Connecting...")
                'If givenNetType = "LAN" Then
                'hisIP = IPAddress.Parse(sqlReader.GetValue(0).ToString())
                'client.Connect(hisIP, 54321)
                'Else
                'hisIP = IPAddress.Parse(sqlReader.GetValue(0).ToString())
                client.Connect(serverLocalIP, 54321)
                'End If
                '   End While
                'sqlConn.Close()
                'Catch ex As Exception
                'MsgBox(ex.Message)
                'End Try
                myprinttext("Ready to play! Wait for other player to make a move...")
                s_stream = client.GetStream()
                waiting = True
            End If
            connected = True

            ' Create new BinaryReaders and asign them to the Network Stream
            s_reader = New BinaryReader(s_stream)
            s_writer = New BinaryWriter(s_stream)
        End Sub
        '
        '   Tranfer from worker thread to main thread to change newGameMenuItem
        '   and resignGameMenuItem
        '
        Private Sub BW_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BW.ProgressChanged
            If e.ProgressPercentage = 1 Then
                ' Set the game state.
                Me.gameState = GameStates.GameOver

                ' Enable/disable the menu items and tool bar buttons as
                ' appropriate.
                Me.newGameMenuItem.Enabled = InlineAssignHelper(Me.playToolBar.Buttons(CInt(ReversiForm.ToolBarButton.NewGame)).Enabled, True)
                Me.resignGameMenuItem.Enabled = InlineAssignHelper(Me.playToolBar.Buttons(CInt(ReversiForm.ToolBarButton.ResignGame)).Enabled, False)
                Me.joinGameMenuItem.Enabled = True

                ' Clear the current player indicator display.
                Me.currentColorTextLabel.Visible = False
                Me.currentColorPanel.BackColor = Color.Empty
                Me.currentColorPanel.Visible = False

                ' Hide the status progress bar.
                Me.statusProgressBar.Visible = False
                Me.statusPanel.Refresh()

                MessageBox.Show("A player resigned...")
            End If
        End Sub
        '
        ' Handles a Closing Connection
        '
        Private Sub close_connection()
            If connected Then
                If iam_server Then
                    server.Stop()
                    ' Close connection with client so that he will now the connection ended
                    connection.Close()
                    iam_server = False
                Else
                    client.Close()
                End If
                connected = False
                BW.ReportProgress(1)
                s_reader.Close()
                s_writer.Close()
                s_stream.Close()
                BW.Dispose()
                myprinttext("Connection lost...")
            End If
        End Sub

        '
        ' Handles a "Join Game" click.
        '
        Private Sub joinGameMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            ' Start a new game.
            ' Start a new game.
            If LoginDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
                givenName = LoginDialog.usernameTextBox.Text
                givenPassword = LoginDialog.passwordTextBox.Text
                givenNetType = LoginDialog.NetTypeCombo.SelectedItem.ToString
                If Not connected Then
                    iam_server = False
                    Me.StartGame()
                    BW.RunWorkerAsync()
                    newGameMenuItem.Enabled = False
                    joinGameMenuItem.Enabled = False
                End If
            End If
            'server.Stop()
            'BW.Dispose()
        End Sub
        '
        ' Handles a "Resign Game" click.
        '
        Private Sub resignGameMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Dim doEnd As Boolean = True

            ' Prompt for confirmation if a game is in progress.
            If Me.gameState <> GameStates.GameOver Then
                ' Create and show the confirm dialog, saving the result.
                Dim dlg As New ConfirmDialog("Resign this game?")
                If dlg.ShowDialog(Me) <> DialogResult.Yes Then
                    doEnd = False
                End If

                dlg.Dispose()
            End If

            ' End the game if the request was not cancelled.
            If doEnd Then

                ' Rreset the board display.
                Me.UnHighlightSquares()
                Me.UpdateBoardDisplay()

                ' Restore Game Menu Items


                ' End the game with the resignation flag set.
                Me.EndGame(True)

                ' Close connection and dispose all resources
                close_connection()
            End If
        End Sub

        '
        ' Handles an "Options..." click.
        '
        Private Sub optionsMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            ' Create the options dialog and set the option controls according
            ' to the current game options.
            Dim dlg As New OptionsDialog(Me.options)

            ' Show the options dialog and if the "OK" button was pressed,
            ' update the game options.
            If dlg.ShowDialog(Me) = DialogResult.OK Then
                ' Update the game options that are safe to change using the
                ' values from the dialog.
                Me.options.ShowValidMoves = dlg.Options.ShowValidMoves
                Me.options.PreviewMoves = dlg.Options.PreviewMoves
                Me.options.BoardColor = dlg.Options.BoardColor
                Me.options.ValidMoveColor = dlg.Options.ValidMoveColor
                Me.options.ActiveSquareColor = dlg.Options.ActiveSquareColor
                Me.options.MoveIndicatorColor = dlg.Options.MoveIndicatorColor

                ' Set the square control colors based on the current color options.
                Me.SetSquareControlColors()

                ' If a game is currently in progress, special handling is
                ' needed for changes to the player options.
                If Me.gameState <> GameStates.GameOver Then
                    ' Lock the board to prevent race conditions.
                    SyncLock Me.board

                        ' Clear any board square highlighting.
                        Me.UnHighlightSquares()

                        ' If the changes to the player options affect the
                        ' current player, restart the current turn.
                        If (dlg.Options.FirstMove <> Me.options.FirstMove AndAlso Me.lastMoveColor = board.Empty) Then

                            ' Set the player options.
                            Me.options.FirstMove = dlg.Options.FirstMove

                            ' If no moves have been made yet, set the current color
                            ' based on the first move option.
                            If Me.lastMoveColor = board.Empty Then
                                Me.currentColor = Me.options.FirstMove
                            End If

                            ' Update the board display.
                            Me.squaresPanel.Refresh()

                            ' Restart the current turn.
                            Me.StartTurn()
                        Else

                            ' Otherwise, set the player options and update the
                            ' board display.
                            ' Set the player options.
                            Me.options.FirstMove = dlg.Options.FirstMove

                            ' Highlight valid moves, if appropriate.
                            If Me.options.ShowValidMoves Then
                                Me.HighlightValidMoves()
                            End If

                            ' Update the board display.	
                            Me.squaresPanel.Refresh()
                        End If
                    End SyncLock
                Else

                    ' A game is not in progress so just set the player options.
                    Me.options.FirstMove = dlg.Options.FirstMove

                    ' Update the board display, in case the colors have been
                    ' changed.
                    Me.squaresPanel.Refresh()
                End If
            End If

            dlg.Dispose()
        End Sub

        '
        ' Handles a "Statistics..." click.
        '
        Private Sub statisticsMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            ' Create and show the statistics dialog.
            Dim dlg As New StatisticsDialog(Me.statistics)
            dlg.ShowDialog(Me)
            dlg.Dispose()
        End Sub

        '
        ' Handles an "Exit" click.
        '
        Private Sub exitMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            ' Close the form.
            Me.Close()
        End Sub
        '
        ' Handles an "About" click.
        '
        Private Sub aboutMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            ' Create and show the about dialog.
            Dim dlg As New AboutDialog()
            dlg.ShowDialog(Me)
            dlg.Dispose()
        End Sub

        '====================================================================
        ' Event handlers for the tool bar.
        '====================================================================

        '
        ' Handles a button click on the tool bar.
        '
        Private Sub playToolBar_ButtonClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ToolBarButtonClickEventArgs)
            ' Determine which button was clicked and simulate a click on the
            ' corresponding menu item.
            Select Case Me.playToolBar.Buttons.IndexOf(e.Button)
                Case CInt(ReversiForm.ToolBarButton.NewGame)
                    Me.newGameMenuItem.PerformClick()
                    Exit Select
                Case CInt(ReversiForm.ToolBarButton.ResignGame)
                    Me.resignGameMenuItem.PerformClick()
                    Exit Select
                Case Else
                    Exit Select
            End Select
        End Sub

        ' ===================================================================
        ' Event handlers for the square controls.
        ' ===================================================================

        '
        ' Handles a mouse move on a board square.
        '

        Private Sub SquareControl_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs)
            RaiseEvent MouseMove(sender, e)

            ' Check the game state to ensure that it is the user's turn.
            If Me.gameState <> GameStates.InPlayerMove Then
                Return
            End If

            Dim squareControl As SquareControl = DirectCast(sender, SquareControl)
            ' If the square is a valid move for the current player,
            ' indicate it.
            If Me.board.IsValidMove(Me.currentColor, squareControl.Row, squareControl.Col) Then
                ' 
                If Not squareControl.IsActive AndAlso squareControl.PreviewContents = board.Empty Then
                    ' If the show valid moves option is active, mark the
                    ' square.
                    If Me.options.ShowValidMoves Then
                        squareControl.IsActive = True

                        ' If the preview moves option is not active, update
                        ' the square display now.
                        If Not Me.options.PreviewMoves Then
                            squareControl.Refresh()
                        End If
                    End If

                    ' If the preview moves option is active, mark the
                    ' appropriate squares.
                    If Me.options.PreviewMoves Then
                        ' Create a temporary board to make the move on.
                        Dim board__1 As New Board(Me.board)
                        board__1.MakeMove(Me.currentColor, squareControl.Row, squareControl.Col)

                        ' Set up the move preview.
                        For i As Integer = 0 To 7
                            For j As Integer = 0 To 7
                                If board__1.GetSquareContents(i, j) <> Me.board.GetSquareContents(i, j) Then
                                    ' Set and update the square display.
                                    Me.squareControls(i, j).PreviewContents = board__1.GetSquareContents(i, j)
                                    Me.squareControls(i, j).Refresh()
                                End If
                            Next
                        Next
                    End If
                End If

                ' Change the cursor.
                squareControl.Cursor = System.Windows.Forms.Cursors.Hand
            End If
        End Sub

        '
        ' Handles a mouse leave on a board square.
        '
        Private Sub SquareControl_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs)
            RaiseEvent MouseLeave(sender, e)

            Dim squareControl As SquareControl = DirectCast(sender, SquareControl)

            ' If the square is currently active, deactivate it.
            If squareControl.IsActive Then
                squareControl.IsActive = False
                squareControl.Refresh()
            End If

            ' If the move is being previewed, clear all affected squares.

            If squareControl.PreviewContents <> board.Empty Then
                ' Clear the move preview.
                For i As Integer = 0 To 7
                    For j As Integer = 0 To 7
                        If Me.squareControls(i, j).PreviewContents <> board.Empty Then
                            Me.squareControls(i, j).PreviewContents = board.Empty
                            Me.squareControls(i, j).Refresh()
                        End If
                    Next
                Next
            End If

            ' Restore the cursor.
            squareControl.Cursor = System.Windows.Forms.Cursors.[Default]
        End Sub

        '
        ' Handles a click on a board square.
        '
        Private Sub SquareControl_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            RaiseEvent Click(sender, e)
            Dim squareControl As SquareControl = DirectCast(sender, SquareControl)

            ' Check if other side is making a move
            If Not waiting And connected And Me.board.IsValidMove(Me.currentColor, squareControl.Row, squareControl.Col) Then
                ' Check the game state to ensure it's the user's turn.
                If Me.gameState <> GameStates.InPlayerMove Then
                    Return
                End If

                'Dim squareControl As SquareControl = DirectCast(sender, SquareControl)

                ' If the move is valid, make it.
                'If Me.board.IsValidMove(Me.currentColor, squareControl.Row, squareControl.Col) Then
                ' Restore the cursor.
                squareControl.Cursor = System.Windows.Forms.Cursors.[Default]


                ' Make the move.
                s_writer.Write(squareControl.Row)
                s_writer.Write(squareControl.Col)
                Me.MakePlayerMove(squareControl.Row, squareControl.Col)
                'End If
                waiting = True
            End If
        End Sub
        Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
            target = value
            Return value
        End Function
    End Class
End Namespace
